<template>
  <div class="page-miH page-bgBack">
    <a-spin :spinning="loading">
      <div class="pageStyle">
        <div class="page-miH" style="min-width: 250px; width: 250px; border-right: 1px solid #e8e8e8">
          <div class="leftBox">
            <div class="searchBox">
              <a-input-search placeholder="搜索保险公司" style="margin-top: 12px" v-model="siteName" @search="getSiteList" />
            </div>
            <div class="siteBox" v-if="siteList && siteList.length">
              <div
                :class="item.isSelected ? 'sitemItemOn' : 'sitemItem'"
                v-for="(item, index) in siteList"
                :key="index"
                @click="siteChange(item, index)"
              >
                {{ item.name }}
              </div>
            </div>
          </div>
        </div>
        <div class="rightBox">
          <div class="detailHead">
            <div class="lineForInfo">
              基本信息
              <div class="line1"></div>
              <a-button :disabled="!siteList.length" v-if="!isShow" type="link" @click="isShow = true">编辑</a-button>
            </div>
            <div>
              <div style="display: flex; justify-content: space-between; padding: 0 100px">
                <div style="display: flex; align-items: center">
                  <div>联系人</div>
                  <a-input
                    :disabled="!isShow"
                    placeholder="请输入"
                    v-model="companyDetail.linkmanName"
                    style="width: 310px; margin-left: 12px"
                  />
                </div>
                <div style="display: flex; align-items: center">
                  <div>联系电话</div>
                  <a-input
                    :disabled="!isShow"
                    placeholder="请输入"
                    v-model="companyDetail.linkmanPhone"
                    style="width: 310px; margin-left: 12px"
                  />
                </div>
              </div>
              <div style="display: flex; align-items: center; padding: 24px 0 24px 38px">
                <div><span style="color: #ff7085">*</span>上传明细表模板</div>
                <a-upload
                  :disabled="!isShow"
                  ref="upload"
                  :file-list="fileList"
                  :headers="headers"
                  action="/file/api/v1/general/upload/attachment"
                  @change="handleChange"
                  accept=".xls, .xlsx"
                  :showUploadList="{
                    showDownloadIcon: true
                  }"
                  @download="download"
                  name="files"
                  style="margin-left: 12px; display: flex; width: 380px"
                >
                  <a-button :disabled="!isShow">{{ !fileList.length ? "上传文件" : "重新上传" }}</a-button>
                </a-upload>
              </div>
              <div v-if="isShow" style="display: flex; justify-content: center; align-items: center; height: 100px">
                <a-button @click="updateCancel">取消</a-button>
                <a-button style="margin-left: 12px" type="primary" @click="updateDetail">保存</a-button>
              </div>
            </div>
          </div>
          <div class="detailBody">
            <div class="lineForInfo">
              保险方案
              <div class="line2"></div>
            </div>
            <div class="functionBtn">
              <a-input-search placeholder="搜索保险方案" v-model="searchPlanName" style="width: 200px" @search="onSearch" />
              <a-button :disabled="!siteList.length" type="primary" @click="addPlan">新增保险方案</a-button>
            </div>
            <div class="planBox" v-if="planList && planList.length">
              <div class="planItem" v-for="(item, index) in planList" :key="index">
                <a-dropdown>
                  <a-menu slot="overlay" @click="(e) => handleMenuClick(e, item)">
                    <a-menu-item key="1">编辑</a-menu-item>
                    <a-menu-item key="2">删除</a-menu-item>
                  </a-menu>
                  <a-icon type="ellipsis" class="funcBtn" />
                </a-dropdown>
                <div class="contentBox">
                  <div>
                    <img style="width: 60px; height: 64px" src="@/assets/admin-icon/planItem.png" alt />
                  </div>
                  <div style="margin-left: 12px; margin-top: 6px">
                    <a-tooltip>
                      <template slot="title">{{ item.schemeName }}</template>
                      <div class="planTitle" style="width: 180px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden">
                        {{ item.schemeName }}
                      </div>
                    </a-tooltip>
                    <div class="planContent" style="display: flex; align-items: center">
                      <div class="planKey">方案明细:</div>
                      <a-popover placement="bottomLeft" title="方案明细">
                        <template slot="content">
                          <div style="display: flex; width: 540px; flex-wrap: wrap">
                            <div
                              style="
                                display: flex;
                                justify-content: space-between;
                                align-items: center;
                                padding: 0 16px;
                                margin: 12px 12px 0 0;
                                width: 254px;
                                height: 41px;
                                background: #f6f6f6;
                                border-radius: 4px;
                              "
                              v-for="(item, index) in item.personTypeList"
                              :key="index"
                            >
                              <a-tooltip>
                                <template slot="title">
                                  {{ item.typeName }}
                                </template>
                                <div
                                  style="
                                    font-size: 14px;
                                    font-weight: 500;
                                    color: #55565d;
                                    width: 98px;
                                    text-overflow: ellipsis;
                                    white-space: nowrap;
                                    overflow: hidden;
                                  "
                                >
                                  {{ item.typeName }}
                                </div>
                              </a-tooltip>
                              <div style="display: flex">
                                <div class="label">实际保险月费:</div>
                                <a-tooltip>
                                  <template slot="title">
                                    <div>{{ item.realityMonthAmount }}</div>
                                  </template>
                                  <div
                                    style="
                                      font-size: 14px;
                                      font-weight: 500;
                                      color: #55565d;
                                      width: 28px;
                                      text-overflow: ellipsis;
                                      white-space: nowrap;
                                      overflow: hidden;
                                    "
                                    class="value"
                                  >
                                    {{ item.realityMonthAmount }}
                                  </div>
                                </a-tooltip>
                              </div>
                            </div>
                          </div>
                        </template>
                        <a-button type="link">查看</a-button>
                      </a-popover>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-else style="padding: 120px 40%">
              <a-empty />
            </div>
            <a-pagination
              style="position: absolute; right: 24px; margin-top: 24px"
              v-model="current"
              :pageSize="9"
              :total="total"
              @change="onPageChange"
            />
          </div>
        </div>
        <a-modal
          v-model="visible"
          :title="title"
          :width="660"
          :okButtonProps="{ props: { disabled: loading_submit } }"
          @ok="handelOk"
          @cancel="visible = false"
        >
          <div class="modalContent">
            <div class="itemContent" style="margin-left: 100px">
              <div class="itemTitle"><span style="color: #fa5051">*</span>保险方案</div>
              <a-input v-model="planItem.schemeName" style="width: 300px; margin-left: 24px" placeholder="请输入" />
            </div>
            <!-- <div class="itemContent" style="margin-left: 70px">
              <div class="itemTitle"><span style="color: #fa5051">*</span>实际保险月费</div>
              <a-input-number
                :precision="2"
                :min="0.01"
                v-model="planItem.realityMonthAmount"
                style="width: 300px; margin-left: 24px"
                placeholder="请输入"
              />
            </div> -->
            <!-- <div style="font-size: 12px; font-weight: 400; color: #a6a8b4; margin-left: 182px; margin-top: 4px">
              保险公司给京普的价格；可放心填写，填写仅用于京普记录
            </div> -->
            <a-alert
              style="margin-left: 50px; margin-top: 24px; width: 526px"
              message="保险公司给京普的价格；可放心填写，填写仅用于京普记录"
              banner
            />
            <div style="margin-left: 50px; margin-top: 12px">
              <div
                style="
                  padding: 0 36px;
                  width: 526px;
                  height: 48px;
                  background: #fafafa;
                  box-shadow: inset 0px -1px 0px 0px #e8e8e8;
                  display: flex;
                  justify-content: flex-start;
                  align-items: center;
                "
              >
                <div style="font-size: 14px; font-weight: 500; color: #252525"><span style="color: #fa5051">*</span>职业分类</div>
                <div style="margin-left: 160px; font-size: 14px; font-weight: 500; color: #252525">
                  <span style="color: #fa5051">*</span>实际保险月费
                </div>
              </div>
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: flex-start;
                  width: 526px;
                  height: 48px;
                  background: #ffffff;
                  box-shadow: inset 0px -1px 0px 0px #e8e8e8;
                "
                v-for="(item, index) in typeList"
                :key="index"
              >
                <a-input v-model="item.typeName" placeholder="请输入" style="width: 180px; margin-left: 36px" />
                <a-input-number v-model="item.realityMonthAmount" placeholder="请输入" style="width: 180px; margin-left: 36px" />
                <a-icon
                  v-if="index > 0"
                  @click="onDelete(item.key)"
                  type="delete"
                  theme="twoTone"
                  two-tone-color="#FA5051"
                  style="margin-left: 28px; cursor: pointer"
                />
                <a-icon
                  v-if="index === typeList.length - 1"
                  @click="handleAdd"
                  type="plus-circle"
                  theme="twoTone"
                  two-tone-color="#6A66F6"
                  style="margin-left: 12px; cursor: pointer"
                />
              </div>
            </div>
          </div>
        </a-modal>
      </div>
    </a-spin>
  </div>
</template>

<script>
import { selectSiteWithInsurance, selectCompanyBySiteId, updateCompanyBySiteId, addPlan, editPlan, getPlan, deletePlan } from "./api";
import { getToken } from "xqjr-module-auth";
import { publicDownLoad } from "../downLoad";
export default {
  data() {
    return {
      siteList: [],
      planList: [],
      visible: false,
      title: "新增保险方案",
      planItem: {},
      companyDetail: {},
      companyDetailCopy: {},
      searchPlanName: undefined,
      current: 1,
      total: 0,
      count: 3,
      typeList: [
        { key: 0, realityMonthAmount: 0, typeName: "1-3类人员" },
        { key: 1, realityMonthAmount: 0, typeName: "4类人员" },
        { key: 2, realityMonthAmount: 0, typeName: "5类人员" }
      ],
      isShow: false,
      fileList: [],
      fileListCopy: [],
      siteName: undefined,
      loading: false,
      detailTemplateFile: undefined,
      detailTemplateFileName: undefined,
      selectSite: {},
      headers: {},
      loading_submit: false
    };
  },
  watch: {
    visible(val) {
      if (val === false) {
        this.getPlan();
      }
    }
  },
  created() {
    this.getSiteList();
    this.headers = {
      token: getToken()
    };
  },
  methods: {
    handleAdd() {
      if (this.typeList.length === 10) {
        this.$message.warning("最多添加10个职业分类");
      } else {
        const { count, typeList } = this;
        const newData = {
          key: count
        };
        this.typeList = [...typeList, newData];
        this.count = count + 1;
      }
    },
    onDelete(key) {
      const typeList = [...this.typeList];
      this.typeList = typeList.filter((item) => item.key !== key);
    },
    download(file) {
      if (file.url) {
        publicDownLoad(file.url);
      } else if (file.response.data && file.response.data[0]) {
        publicDownLoad(file.response.data[0]);
      } else {
        this.$message.warning("文件下载失败");
      }
    },
    handleChange(info) {
      let fileList = [...info.fileList];
      fileList = fileList.slice(-1);
      fileList = fileList.map((file) => {
        if (file.response) {
          file.url = file.response.url;
        }
        return file;
      });
      this.fileList = fileList;
      if (this.fileList && this.fileList.length) {
        if (this.fileList[0].status === "done" && this.fileList[0].response.data && this.fileList[0].response.data[0]) {
          this.detailTemplateFile = this.fileList[0].response.data[0];
          this.detailTemplateFileName = this.fileList[0].name;
        }
      } else {
        this.detailTemplateFile = "";
        this.detailTemplateFileName = "";
      }
    },
    onPageChange() {
      this.getDetail(this.selectSite.id);
    },
    siteChange(item, index) {
      this.siteList.forEach((e, idx) => {
        if (idx === index) {
          e.isSelected = true;
          this.current = 1;
          this.getDetail(e.id);
          this.selectSite = e;
        } else {
          e.isSelected = false;
        }
      });
    },
    getSiteList() {
      selectSiteWithInsurance({
        siteName: this.siteName
      })
        .then((res) => {
          this.siteList = res.data;
          if (this.siteList && this.siteList.length) {
            this.siteList[0].isSelected = true;
            this.getDetail(this.siteList[0].id);
            this.selectSite = this.siteList[0];
            // this.getPlan();
          } else {
            this.getDetail();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getDetail(id) {
      this.loading = true;
      if (id) {
        selectCompanyBySiteId(id)
          .then((res) => {
            this.companyDetail = JSON.parse(JSON.stringify(res.data));
            this.companyDetailCopy = JSON.parse(JSON.stringify(res.data));
            this.getPlan();
            this.detailTemplateFile = res.data.detailTemplateFile;
            this.detailTemplateFileName = res.data.remark;
            if (this.detailTemplateFileName && this.detailTemplateFile) {
              this.fileList = [
                {
                  uid: "1",
                  name: this.detailTemplateFileName,
                  status: "done",
                  response: "Server Error 500",
                  url: this.detailTemplateFile
                }
              ];
            } else {
              this.fileList = [];
            }
            this.fileListCopy = this.fileList;
            this.loading = false;
          })
          .catch((err) => {
            this.loading = false;
            console.log(err);
          });
      } else {
        this.companyDetail = {};
        this.companyDetailCopy = {};
        this.detailTemplateFile = null;
        this.detailTemplateFileName = null;
        this.planList = [];
        this.total = 0;
        this.fileList = [];
        this.loading = false;
      }
    },
    updateCancel() {
      this.fileList = JSON.parse(JSON.stringify(this.fileListCopy));
      this.companyDetail = JSON.parse(JSON.stringify(this.companyDetailCopy));
      this.isShow = false;
    },
    updateDetail() {
      if (!this.fileList.length) {
        this.$message.warning("请上传明细表模板");
      } else {
        updateCompanyBySiteId({
          id: this.companyDetail.id,
          companySiteId: this.selectSite.id,
          companyName: this.selectSite.name,
          linkmanName: this.companyDetail.linkmanName,
          linkmanPhone: this.companyDetail.linkmanPhone,
          detailTemplateFile: this.detailTemplateFile,
          remark: this.detailTemplateFileName
        })
          .then((res) => {
            this.$message.success("编辑成功");
            this.getDetail(this.selectSite.id);
            this.isShow = false;
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },

    getPlan() {
      getPlan({ companyId: this.companyDetail.id, pageSize: 9, pageNo: this.current, schemeName: this.searchPlanName }).then((res) => {
        if (res.data.entities.length === 0 && this.current > 1) {
          // 当本页非第一页（比第一页大）时，删除最后一条后台会返回当页页码，
          // 但是本页数据为空，table组件会展示为当前页的上一页数据为空，需要加加判断再拉一下上页数据
          this.current = this.current - 1;
          this.pageSize = 9;
          this.getPlan();
        } else {
          this.planList = res.data.entities;
          this.total = res.data.entityCount;
        }
      });
    },
    addPlan() {
      this.visible = true;
      this.title = "新增保险方案";
      this.planItem = {};
      this.count = 3;
      this.typeList = [
        { key: 0, realityMonthAmount: 0, typeName: "1-3类人员" },
        { key: 1, realityMonthAmount: 0, typeName: "4类人员" },
        { key: 2, realityMonthAmount: 0, typeName: "5类人员" }
      ];
    },
    handelOk() {
      var hasName = true;
      var haAmount = true;
      var isZero = true;
      this.typeList.forEach((item) => {
        if (!item.typeName) {
          hasName = false;
        } else if (!item.realityMonthAmount && item.realityMonthAmount !== 0) {
          haAmount = false;
        } else if (item.realityMonthAmount === 0) {
          isZero = false;
        }
      });
      if (!hasName) {
        this.$message.warning("请填写职业分类名称");
      } else if (!haAmount) {
        this.$message.warning("请填写实际保险月费");
      } else if (!isZero) {
        this.$message.warning("实际保险月费不能为0");
      } else if (!this.planItem.schemeName) {
        this.$message.warning("请填写保险方案");
      } else {
        var arr = { ...this.planItem, insCompanyId: this.companyDetail.id, personTypeList: this.typeList };
        this.loading_submit = true;
        if (this.title === "新增保险方案") {
          addPlan(arr)
            .then((res) => {
              this.$message.success("新增成功");
              this.visible = false;
              this.getPlan();
              this.loading_submit = false;
            })
            .catch((err) => {
              this.loading_submit = false;
              console.log(err);
            });
        } else {
          editPlan(arr)
            .then((res) => {
              this.$message.success("编辑成功");
              this.visible = false;
              this.getPlan();
              this.loading_submit = false;
            })
            .catch((err) => {
              this.loading_submit = false;
              console.log(err);
            });
        }
      }
    },
    onSearch() {
      this.current = 1;
      this.getPlan();
    },
    handleMenuClick(e, item) {
      if (e.key === "1") {
        this.visible = true;
        this.title = "编辑保险方案";
        this.planItem = {
          schemeName: item.schemeName,
          realityMonthAmount: item.realityMonthAmount ? item.realityMonthAmount : undefined,
          id: item.id
        };
        item.personTypeList.forEach((item, index) => {
          item.key = index;
        });
        this.typeList = item.personTypeList;
        this.count = item.personTypeList.length;
      } else if (e.key === "2") {
        var that = this;
        this.$confirm({
          title: "确定删除此投保方案吗?",
          content: (h) => <div style="color:red;">{item.schemeName}</div>,
          onOk() {
            deletePlan(item.id).then((res) => {
              that.getPlan();
              that.$message.success("删除成功");
            });
          },
          onCancel() {
            console.log("Cancel");
          },
          class: "test"
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.label {
  height: 14px;
  font-size: 14px;
  font-weight: 400;
  color: #a6a8b4;
}
.value {
  font-size: 14px;
  font-weight: 400;
  color: #636572;
}
.pageStyle {
  padding: 24px 0;
  display: flex;
}
.addIcon {
  cursor: pointer;
  color: var(--primary);
}
.leftBox {
  .searchBox {
    padding: 0 24px;
  }
  .siteBox {
    margin-top: 8px;
    height: 700px;
    overflow: auto;
    .sitemItem {
      cursor: pointer;
      height: 40px;
      line-height: 40px;
      padding-left: 24px;
      font-size: 14px;
      font-weight: 400;
      border-bottom: 1px solid #e8e8e8;
    }
    .sitemItemOn {
      cursor: pointer;
      height: 40px;
      line-height: 40px;
      padding-left: 24px;
      font-size: 14px;
      font-weight: 400;
      background-color: var(--primary10);
      border-bottom: none;
    }
    .sitemItem:hover {
      background-color: var(--primary10);
      border-bottom: none;
    }
  }
}
.modalContent {
  .itemContent {
    display: flex;
    align-items: center;
    margin-top: 24px;
    .itemTitle {
      font-size: 14px;
      font-weight: 400;
    }
  }
}
.rightBox {
  padding: 0 24px;
  width: 100%;
  .lineForInfo {
    margin-bottom: 24px;
    font-size: 16px;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);
    border-left: 3px solid var(--primary);
    padding-left: 8px;
    height: 18px;
    line-height: 18px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .line1 {
      width: 88%;
      background: #e8e8e8;
      height: 1px;
    }
    .line2 {
      width: 93%;
      background: #e8e8e8;
      height: 1px;
    }
  }
  .functionBtn {
    display: flex;
    justify-content: space-between;
  }
  .planBox {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    .planItem {
      margin-top: 24px;
      width: 31%;
      height: 108px;
      margin-left: 24px;
      border-radius: 3px;
      border: 1px solid #e8e8e8;
      position: relative;
      .funcBtn {
        cursor: pointer;
        position: absolute;
        top: 0;
        right: 0;
        font-size: 18px;
        margin-top: 12px;
        margin-right: 12px;
      }
      .contentBox {
        margin-top: 24px;
        margin-left: 18px;
        display: flex;
        justify-content: flex-start;
        .planTitle {
          font-size: 14px;
          font-weight: 500;
          color: #3c3d43;
        }
        .planContent {
          display: flex;
          margin-top: 4px;
          .planKey {
            font-size: 14px;
            font-weight: 400;
            color: #a6a8b4;
          }
          .planValue {
            font-size: 14px;
            font-weight: 400;
            color: #636572;
          }
        }
      }
    }
  }
}
</style>
